import mongoose from 'mongoose';
import colors from 'colors';

import config from '../config';
import { initMongoData, } from './dataInit';

mongoose.connect(config.url);
mongoose.Promise = global.Promise;

const db = mongoose.connection;

db.once('open' ,() => {
  initMongoData();
	console.log(
    colors.green('连接数据库成功')
  );
});

db.on('error', function(error) {
    console.error(
      colors.red(`Error in MongoDb connection: ${error}`)
    );
    mongoose.disconnect();
});

db.on('close', function() {
    console.log(
      colors.red('数据库断开，重新连接数据库')
    );
    mongoose.connect(config.url, {server:{auto_reconnect:true}});
});

export default db;
